<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Inziu Iosevka Slab SC:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="scikit-learn,note," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="Some popular groups of models provided by scikit-learn include:  Clustering: for grouping unlabeled data such as KMeans. Cross Validation: for estimating the performance of supervised models on unseen">
<meta name="keywords" content="scikit-learn,note">
<meta property="og:type" content="article">
<meta property="og:title" content="Scikit Learn Tutorials">
<meta property="og:url" content="http://idmk.oschina.io/2017/09/06/scikit-learn-Tutorials/index.html">
<meta property="og:site_name" content="苦舟">
<meta property="og:description" content="Some popular groups of models provided by scikit-learn include:  Clustering: for grouping unlabeled data such as KMeans. Cross Validation: for estimating the performance of supervised models on unseen">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://idmk.oschina.io/2017/09/06/scikit-learn-Tutorials/markdown-img-paste-20170906102850840.png">
<meta property="og:updated_time" content="2017-11-22T15:33:54.415Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Scikit Learn Tutorials">
<meta name="twitter:description" content="Some popular groups of models provided by scikit-learn include:  Clustering: for grouping unlabeled data such as KMeans. Cross Validation: for estimating the performance of supervised models on unseen">
<meta name="twitter:image" content="http://idmk.oschina.io/2017/09/06/scikit-learn-Tutorials/markdown-img-paste-20170906102850840.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://idmk.oschina.io/2017/09/06/scikit-learn-Tutorials/"/>





  <title>Scikit Learn Tutorials | 苦舟</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">苦舟</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学海无涯，吾将上下求索。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://idmk.oschina.io/2017/09/06/scikit-learn-Tutorials/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="东木金">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苦舟">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Scikit Learn Tutorials</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-09-06T09:21:03+08:00">
                2017-09-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/ML/" itemprop="url" rel="index">
                    <span itemprop="name">ML</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Some popular groups of models provided by scikit-learn include:</p>
<ol>
<li>Clustering: for grouping unlabeled data such as KMeans.</li>
<li>Cross Validation: for estimating the performance of supervised models on unseen data.</li>
<li>Datasets: for test datasets and for generating datasets with specific properties for investigating model behavior.</li>
<li>Dimensionality Reduction: for reducing the number of attributes in data for summarization, visualization and feature selection such as Principal component analysis.</li>
<li>Ensemble methods: for combining the predictions of multiple supervised models.</li>
<li>Feature extraction: for defining attributes in image and text data.</li>
<li>Feature selection: for identifying meaningful attributes from which to create supervised models.</li>
<li>Parameter Tuning: for getting the most out of supervised models.</li>
<li>Manifold Learning: For summarizing and depicting complex multi-dimensional data.</li>
<li>Supervised Models: a vast array not limited to generalized linear models, discriminate analysis, naive bayes, lazy methods, neural networks, support vector machines and decision trees.</li>
</ol>
<a id="more"></a>
<h2 id="Outline"><a href="#Outline" class="headerlink" title="Outline"></a>Outline</h2><ul>
<li>A tutorial on statistical-learning for scientific data processing<ul>
<li>Statistical learning: the setting and the estimator object in scikit-learn</li>
<li>Supervised learning: predicting an output variable from high-dimensional observations</li>
<li>Model selection: choosing estimators and their parameters</li>
<li>Unsupervised learning: seeking representations of the data</li>
<li>Putting it all together</li>
</ul>
</li>
<li>Working With Text Data<ul>
<li>Tutorial setup</li>
<li>Loading the 20 newsgroups dataset</li>
<li>Extracting features from text files</li>
<li>Training a classifier</li>
<li>Building a pipeline</li>
<li>Evaluation of the performance on the test set</li>
<li>Parameter tuning using grid search</li>
<li>Exercise 1: Language identification</li>
<li>Exercise 2: Sentiment Analysis on movie reviews</li>
<li>Exercise 3: CLI text classification utility</li>
<li>Where to from here</li>
</ul>
</li>
</ul>
<h2 id="A-tutorial-on-statistical-learning-for-scientific-data"><a href="#A-tutorial-on-statistical-learning-for-scientific-data" class="headerlink" title="A tutorial on statistical-learning for scientific data"></a>A tutorial on statistical-learning for scientific data</h2><h3 id="the-setting-and-the-estimator-object-in-scikit-learn"><a href="#the-setting-and-the-estimator-object-in-scikit-learn" class="headerlink" title="the setting and the estimator object in scikit-learn"></a>the setting and the estimator object in scikit-learn</h3><h4 id="Datasets"><a href="#Datasets" class="headerlink" title="Datasets"></a>Datasets</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; from sklearn import datasets</div><div class="line">&gt;&gt;&gt; iris = datasets.load_iris()</div><div class="line">&gt;&gt;&gt; data = iris.data</div><div class="line">&gt;&gt;&gt; data.shape</div><div class="line">(150, 4)</div></pre></td></tr></table></figure>
<h4 id="reshaping-data"><a href="#reshaping-data" class="headerlink" title="reshaping data"></a>reshaping data</h4><p>The digits dataset is made of 1797 8x8 images of hand-written digits. To use this dataset with the scikit, we transform each 8x8 image into a feature vector of length 64.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; digits = datasets.load_digits()</div><div class="line">&gt;&gt;&gt; digits.images.shape</div><div class="line">(1797, 8, 8)</div><div class="line">&gt;&gt;&gt; data = digits.images.reshape((digits.images.shape[0], -1))</div></pre></td></tr></table></figure></p>
<h3 id="Supervised-learning-predicting-an-output-variable-from-high-dimensional-observations"><a href="#Supervised-learning-predicting-an-output-variable-from-high-dimensional-observations" class="headerlink" title="Supervised learning: predicting an output variable from high-dimensional observations"></a>Supervised learning: predicting an output variable from high-dimensional observations</h3><p>Nearest neighbor and the curse of dimensionality<br>Linear model: from regression (shrinkage) to sparsity<br>Support vector machines (SVMs):Linear SVMs, Using kernels.</p>
<h4 id="Source"><a href="#Source" class="headerlink" title="Source"></a>Source</h4><p><a href="http://sklearn.lzjqsdd.com/tutorial/statistical_inference/supervised_learning.html" target="_blank" rel="external">http://sklearn.lzjqsdd.com/tutorial/statistical_inference/supervised_learning.html</a></p>
<h3 id="Model-selection-choosing-estimators-and-their-parameters"><a href="#Model-selection-choosing-estimators-and-their-parameters" class="headerlink" title="Model selection: choosing estimators and their parameters"></a>Model selection: choosing estimators and their parameters</h3><p>score: 模型在新数据上的泛化能力，用于交叉验证。</p>
<h4 id="Score-and-cross-validated-scores"><a href="#Score-and-cross-validated-scores" class="headerlink" title="Score, and cross-validated scores"></a>Score, and cross-validated scores</h4><p>As we have seen, every estimator exposes a score method that can judge the quality of the fit (or the prediction) on new data. Bigger is better.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; from sklearn import datasets, svm</div><div class="line">&gt;&gt;&gt; digits = datasets.load_digits()</div><div class="line">&gt;&gt;&gt; X_digits = digits.data</div><div class="line">&gt;&gt;&gt; y_digits = digits.target</div><div class="line">&gt;&gt;&gt; svc = svm.SVC(C=1, kernel=&apos;linear&apos;)</div><div class="line">&gt;&gt;&gt; svc.fit(X_digits[:-100], y_digits[:-100]).score(X_digits[-100:], y_digits[-100:])</div><div class="line">0.97999999999999998</div></pre></td></tr></table></figure>
<h5 id="KFold-cross-validation"><a href="#KFold-cross-validation" class="headerlink" title="KFold cross validation"></a>KFold cross validation</h5><p>To get a better measure of prediction accuracy (which we can use as a proxy for goodness of fit of the model), we can successively split the data in folds that we use for training and testing.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; import numpy as np</div><div class="line">&gt;&gt;&gt; X_folds = np.array_split(X_digits, 3)</div><div class="line">&gt;&gt;&gt; y_folds = np.array_split(y_digits, 3)</div><div class="line">&gt;&gt;&gt; scores = list()</div><div class="line">&gt;&gt;&gt; for k in range(3):</div><div class="line">...     # We use &apos;list&apos; to copy, in order to &apos;pop&apos; later on</div><div class="line">...     X_train = list(X_folds)</div><div class="line">...     X_test  = X_train.pop(k)</div><div class="line">...     X_train = np.concatenate(X_train)</div><div class="line">...     y_train = list(y_folds)</div><div class="line">...     y_test  = y_train.pop(k)</div><div class="line">...     y_train = np.concatenate(y_train)</div><div class="line">...     scores.append(svc.fit(X_train, y_train).score(X_test, y_test))</div><div class="line">&gt;&gt;&gt;</div><div class="line">&gt;&gt;&gt; print(scores)</div><div class="line">[0.93489148580968284, 0.95659432387312182, 0.93989983305509184]</div></pre></td></tr></table></figure></p>
<h4 id="Cross-validation-generators"><a href="#Cross-validation-generators" class="headerlink" title="Cross-validation generators"></a>Cross-validation generators</h4><p>The code above to split data in train and test sets is tedious to write. Scikit-learn exposes cross-validation generators to generate list of indices for this purpose:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; from sklearn import cross_validation</div><div class="line">&gt;&gt;&gt; k_fold = cross_validation.KFold(n=6, n_folds=3)</div><div class="line">&gt;&gt;&gt; for train_indices, test_indices in k_fold:</div><div class="line">...      print(&apos;Train: %s | test: %s&apos; % (train_indices, test_indices))</div><div class="line">Train: [2 3 4 5] | test: [0 1]</div><div class="line">Train: [0 1 4 5] | test: [2 3]</div><div class="line">Train: [0 1 2 3] | test: [4 5]</div></pre></td></tr></table></figure></p>
<p>The cross-validation can then be implemented easily:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; kfold = cross_validation.KFold(len(X_digits), n_folds=3)</div><div class="line">&gt;&gt;&gt; [svc.fit(X_digits[train], y_digits[train]).score(X_digits[test], y_digits[test])</div><div class="line">...          for train, test in kfold]</div><div class="line">[0.93489148580968284, 0.95659432387312182, 0.93989983305509184]</div></pre></td></tr></table></figure></p>
<p>To compute the score method of an estimator, the sklearn exposes a helper function:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; cross_validation.cross_val_score(svc, X_digits, y_digits, cv=kfold, n_jobs=-1)</div><div class="line">array([ 0.93489149,  0.95659432,  0.93989983])</div></pre></td></tr></table></figure></p>
<p>n_jobs=-1 means that the computation will be dispatched on all the CPUs of the computer.</p>
<h4 id="Cross-validation-generators-1"><a href="#Cross-validation-generators-1" class="headerlink" title="Cross-validation generators"></a>Cross-validation generators</h4><table>
<thead>
<tr>
<th style="text-align:center">KFold (n, k)</th>
<th style="text-align:center">StratifiedKFold (y, k)</th>
<th style="text-align:center">LeaveOneOut (n)</th>
<th style="text-align:center">LeaveOneLabelOut (labels)</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">Split it K folds, train on K-1 and then test on left-out</td>
<td style="text-align:center">It preserves the class ratios / label distribution within each fold.</td>
<td style="text-align:center">Leave one observation out</td>
<td style="text-align:center">Takes a label array to group observations</td>
</tr>
</tbody>
</table>
<h4 id="Grid-search-and-cross-validated-estimators"><a href="#Grid-search-and-cross-validated-estimators" class="headerlink" title="Grid-search and cross-validated estimators"></a>Grid-search and cross-validated estimators</h4><p>The sklearn provides an object that, given data, computes the score during the fit of an estimator on a parameter grid and <strong>chooses the parameters to maximize the cross-validation score</strong>. This object takes an estimator during the construction and exposes an estimator API:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; from sklearn.grid_search import GridSearchCV</div><div class="line">&gt;&gt;&gt; Cs = np.logspace(-6, -1, 10)</div><div class="line">&gt;&gt;&gt; clf = GridSearchCV(estimator=svc, param_grid=dict(C=Cs),</div><div class="line">...                    n_jobs=-1)</div><div class="line">&gt;&gt;&gt; clf.fit(X_digits[:1000], y_digits[:1000])</div><div class="line">GridSearchCV(cv=None,...</div><div class="line">&gt;&gt;&gt; clf.best_score_</div><div class="line">0.925...</div><div class="line">&gt;&gt;&gt; clf.best_estimator_.C</div><div class="line">0.0077...</div><div class="line"></div><div class="line">&gt;&gt;&gt; # Prediction performance on test set is not as good as on train set</div><div class="line">&gt;&gt;&gt; clf.score(X_digits[1000:], y_digits[1000:])</div><div class="line">0.943...</div></pre></td></tr></table></figure></p>
<p>By default, the <a href="http://sklearn.lzjqsdd.com/modules/generated/sklearn.grid_search.GridSearchCV.html#sklearn.grid_search.GridSearchCV" target="_blank" rel="external">GridSearchCV</a> uses a 3-fold cross-validation. However, if it detects that a classifier is passed, rather than a regressor, it uses a stratified 3-fold.</p>
<p>Nested cross-validation<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; cross_validation.cross_val_score(clf, X_digits, y_digits)</div><div class="line">...</div><div class="line">array([ 0.938...,  0.963...,  0.944...])</div></pre></td></tr></table></figure></p>
<h4 id="Source-1"><a href="#Source-1" class="headerlink" title="Source"></a>Source</h4><p><a href="http://sklearn.lzjqsdd.com/tutorial/statistical_inference/model_selection.html" target="_blank" rel="external">http://sklearn.lzjqsdd.com/tutorial/statistical_inference/model_selection.html</a></p>
<h3 id="Unsupervised-learning-seeking-representations-of-the-data"><a href="#Unsupervised-learning-seeking-representations-of-the-data" class="headerlink" title="Unsupervised learning: seeking representations of the data"></a>Unsupervised learning: seeking representations of the data</h3><h4 id="Clustering-grouping-observations-together"><a href="#Clustering-grouping-observations-together" class="headerlink" title="Clustering: grouping observations together"></a>Clustering: grouping observations together</h4><p>The problem solved in clustering<br>Given the iris dataset, if we knew that there were 3 types of iris, but did not have access to a taxonomist to label them: we could try a clustering task: split the observations into well-separated group called clusters.</p>
<p>Note that there exist a lot of different clustering criteria and associated algorithms. The simplest clustering algorithm is K-means.</p>
<h4 id="K-means-clustering"><a href="#K-means-clustering" class="headerlink" title="K-means clustering"></a><a href="http://sklearn.lzjqsdd.com/modules/clustering.html#k-means" target="_blank" rel="external">K-means clustering</a></h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; from sklearn import cluster, datasets</div><div class="line">&gt;&gt;&gt; iris = datasets.load_iris()</div><div class="line">&gt;&gt;&gt; X_iris = iris.data</div><div class="line">&gt;&gt;&gt; y_iris = iris.target</div><div class="line"></div><div class="line">&gt;&gt;&gt; k_means = cluster.KMeans(n_clusters=3)</div><div class="line">&gt;&gt;&gt; k_means.fit(X_iris)</div><div class="line">KMeans(copy_x=True, init=&apos;k-means++&apos;, ...</div><div class="line">&gt;&gt;&gt; print(k_means.labels_[::10])</div><div class="line">[1 1 1 1 1 0 0 0 0 0 2 2 2 2 2]</div><div class="line">&gt;&gt;&gt; print(y_iris[::10])</div><div class="line">[0 0 0 0 0 1 1 1 1 1 2 2 2 2 2]</div></pre></td></tr></table></figure>
<p>Warning There is absolutely no guarantee of recovering a ground truth. First, choosing the right number of clusters is hard. Second, the algorithm is sensitive to initialization, and can fall into local minima, although scikit-learn employs several tricks to mitigate this issue.</p>
<h4 id="Decompositions-from-a-signal-to-components-and-loadings"><a href="#Decompositions-from-a-signal-to-components-and-loadings" class="headerlink" title="Decompositions: from a signal to components and loadings"></a>Decompositions: from a signal to components and loadings</h4><p>Components and loadings:<br>If X is our multivariate data, then the problem that we are trying to solve is to rewrite it on a different observational basis: we want to learn loadings L and a set of components C such that X = L C. Different criteria exist to choose the components</p>
<h5 id="Principal-component-analysis-PCA"><a href="#Principal-component-analysis-PCA" class="headerlink" title="Principal component analysis: PCA"></a><a href="http://sklearn.lzjqsdd.com/modules/decomposition.html#pca" target="_blank" rel="external">Principal component analysis: PCA</a></h5><p>Principal component analysis (PCA) selects the successive components that explain the maximum variance in the signal.</p>
<p>The point cloud spanned by the observations above is very flat in one direction: one of the three univariate features can almost be exactly computed using the other two. PCA finds the directions in which the data is not flat.</p>
<p>When used to transform data, PCA can reduce the dimensionality of the data by projecting on a principal subspace.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; # Create a signal with only 2 useful dimensions</div><div class="line">&gt;&gt;&gt; x1 = np.random.normal(size=100)</div><div class="line">&gt;&gt;&gt; x2 = np.random.normal(size=100)</div><div class="line">&gt;&gt;&gt; x3 = x1 + x2</div><div class="line">&gt;&gt;&gt; X = np.c_[x1, x2, x3]</div><div class="line"></div><div class="line">&gt;&gt;&gt; from sklearn import decomposition</div><div class="line">&gt;&gt;&gt; pca = decomposition.PCA()</div><div class="line">&gt;&gt;&gt; pca.fit(X)</div><div class="line">PCA(copy=True, n_components=None, whiten=False)</div><div class="line">&gt;&gt;&gt; print(pca.explained_variance_)</div><div class="line">[  2.18565811e+00   1.19346747e+00   8.43026679e-32]</div><div class="line"></div><div class="line">&gt;&gt;&gt; # As we can see, only the 2 first components are useful</div><div class="line">&gt;&gt;&gt; pca.n_components = 2</div><div class="line">&gt;&gt;&gt; X_reduced = pca.fit_transform(X)</div><div class="line">&gt;&gt;&gt; X_reduced.shape</div><div class="line">(100, 2)</div></pre></td></tr></table></figure>
<h5 id="Independent-Component-Analysis-ICA"><a href="#Independent-Component-Analysis-ICA" class="headerlink" title="Independent Component Analysis: ICA"></a><a href="http://sklearn.lzjqsdd.com/modules/decomposition.html#ica" target="_blank" rel="external">Independent Component Analysis: ICA</a></h5><p>Independent component analysis (ICA) selects components so that the distribution of their loadings carries a maximum amount of independent information. It is able to recover non-Gaussian independent signals:<br><img src="/2017/09/06/scikit-learn-Tutorials/markdown-img-paste-20170906102850840.png" alt="markdown-img-paste-20170906102850840.png" title=""></p>
<h4 id="Source-2"><a href="#Source-2" class="headerlink" title="Source"></a>Source</h4><p><a href="http://sklearn.lzjqsdd.com/tutorial/statistical_inference/unsupervised_learning.html" target="_blank" rel="external">http://sklearn.lzjqsdd.com/tutorial/statistical_inference/unsupervised_learning.html</a></p>
<h3 id="Putting-it-all-together"><a href="#Putting-it-all-together" class="headerlink" title="Putting it all together"></a>Putting it all together</h3><h4 id="Pipelining"><a href="#Pipelining" class="headerlink" title="Pipelining"></a>Pipelining</h4><p>We have seen that some estimators can transform data and that some estimators can predict variables. We can also create combined estimators:</p>
<h4 id="Face-recognition-with-eigenfaces"><a href="#Face-recognition-with-eigenfaces" class="headerlink" title="Face recognition with eigenfaces"></a><a href="http://sklearn.lzjqsdd.com/tutorial/statistical_inference/putting_together.html#face-recognition-with-eigenfaces" target="_blank" rel="external">Face recognition with eigenfaces</a></h4><p>The dataset used in this example is a preprocessed excerpt of the “ Labeled Faces in the Wild ” , also known as LFW:<br><a href="http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz" target="_blank" rel="external">http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz</a> (233MB)<br>已下载至：<code>D:tmp</code></p>
<h2 id="Working-With-Text-Data"><a href="#Working-With-Text-Data" class="headerlink" title="Working With Text Data"></a>Working With Text Data</h2><h3 id="Working-With-Text-Data-1"><a href="#Working-With-Text-Data-1" class="headerlink" title="Working With Text Data"></a>Working With Text Data</h3><p>The goal of this guide is to explore some of the main scikit-learn tools on a single practical task: analysing a collection of text documents (newsgroups posts) on twenty different topics.<br>In this section we will see how to:</p>
<ul>
<li>load the file contents and the categories</li>
<li>extract feature vectors suitable for machine learning</li>
<li>train a linear model to perform categorization</li>
<li>use a grid search strategy to find a good configuration of both the feature extraction components and the classifier</li>
</ul>
<p>Tutorial setup</p>
<p>The source of this tutorial can be found within your scikit-learn folder:<br><code>scikit-learn/doc/tutorial/text_analytics/</code></p>
<p>The tutorial folder, should contain the following folders:</p>
<ul>
<li>*.rst files - the source of the tutorial document written with sphinx</li>
<li>data - folder to put the datasets used during the tutorial</li>
<li>skeletons - sample incomplete scripts for the exercises</li>
<li>solutions - solutions of the exercises</li>
</ul>
<p>You can already copy the skeletons into a new folder somewhere on your hard-drive named sklearn_tut_workspace where you will edit your own files for the exercises while keeping the original skeletons intact:</p>
<h3 id="Extracting-features-from-text-files"><a href="#Extracting-features-from-text-files" class="headerlink" title="Extracting features from text files"></a>Extracting features from text files</h3><h4 id="Bags-of-words"><a href="#Bags-of-words" class="headerlink" title="Bags of words"></a>Bags of words</h4><p>If n_samples == 10000, storing X as a numpy array of type float32 would require 10000 x 100000 x 4 bytes = 4GB in RAM which is barely manageable on today ’ s computers.<br>Fortunately, most values in X will be zeros since for a given document less than a couple thousands of distinct words will be used. For this reason we say that bags of words are typically high-dimensional sparse datasets. We can save a lot of memory by only storing the non-zero parts of the feature vectors in memory.<br><code>scipy.sparse</code> matrices are data structures that do exactly this, and scikit-learn has built-in support for these structures.</p>
<p>Tokenizing text with scikit-learn<br><code>Text preprocessing, tokenizing and filtering of stopwords</code> are included in a high level component that is able to build a dictionary of features and transform documents to feature vectors:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&gt;&gt;&gt; from sklearn.feature_extraction.text import CountVectorizer</div><div class="line">&gt;&gt;&gt; count_vect = CountVectorizer()</div><div class="line">&gt;&gt;&gt; X_train_counts = count_vect.fit_transform(twenty_train.data)</div><div class="line">&gt;&gt;&gt; X_train_counts.shape</div><div class="line">(2257, 35788)</div></pre></td></tr></table></figure></p>
<p><a href="http://sklearn.lzjqsdd.com/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer" target="_blank" rel="external">CountVectorizer</a> supports counts of N-grams of words or consequective characters. Once fitted, the vectorizer has built a dictionary of feature indices:</p>
<p>categories = [‘alt.atheism’, ‘soc.religion.christian’, ‘comp.graphics’, ‘sci.med’]<br>from sklearn.datasets import fetch_20newsgroups<br>twenty_train = fetch_20newsgroups(subset=’train’, categories=categories, shuffle=True, random_state=42)</p>
<p>from sklearn.feature_extraction.text import CountVectorizer<br>count_vect = CountVectorizer()<br>X_train_counts = count_vect.fit_transform(twenty_train.data)<br>X_train_counts.shape<br>(2257, 35788)</p>
<h2 id="Choosing-the-right-estimator"><a href="#Choosing-the-right-estimator" class="headerlink" title="Choosing the right estimator"></a>Choosing the right estimator</h2><p>Often the hardest part of solving a machine learning problem can be finding the right estimator for the job.<br>Different estimators are better suited for different types of data and different problems.<br>The flowchart below is designed to give users a bit of a rough guide on how to approach problems with regard to which estimators to try on your data.<br>Click on any estimator in the chart below to see it ’ s documentation.<br><a href="http://sklearn.lzjqsdd.com/tutorial/machine_learning_map/index.html" target="_blank" rel="external">http://sklearn.lzjqsdd.com/tutorial/machine_learning_map/index.html</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/scikit-learn/" rel="tag"># scikit-learn</a>
          
            <a href="/tags/note/" rel="tag"># note</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/09/04/SVM-In-Sklearn/" rel="next" title="SVM in Sklearn">
                <i class="fa fa-chevron-left"></i> SVM in Sklearn
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/09/06/Generalized-Linear-Models-In-Scikit-Learn/" rel="prev" title="Generalized Linear Models in Scikit Learn">
                Generalized Linear Models in Scikit Learn <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="东木金" />
          <p class="site-author-name" itemprop="name">东木金</p>
           
              <p class="site-description motion-element" itemprop="description">正在学习机器学习，希望能变得很强！</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">162</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">18</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">42</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/bdmk" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:catcherchan94@outlook.com" target="_blank" title="E-Mail">
                  
                    <i class="fa fa-fw fa-envelope"></i>
                  
                    
                      E-Mail
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Outline"><span class="nav-number">1.</span> <span class="nav-text">Outline</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#A-tutorial-on-statistical-learning-for-scientific-data"><span class="nav-number">2.</span> <span class="nav-text">A tutorial on statistical-learning for scientific data</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#the-setting-and-the-estimator-object-in-scikit-learn"><span class="nav-number">2.1.</span> <span class="nav-text">the setting and the estimator object in scikit-learn</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Datasets"><span class="nav-number">2.1.1.</span> <span class="nav-text">Datasets</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#reshaping-data"><span class="nav-number">2.1.2.</span> <span class="nav-text">reshaping data</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Supervised-learning-predicting-an-output-variable-from-high-dimensional-observations"><span class="nav-number">2.2.</span> <span class="nav-text">Supervised learning: predicting an output variable from high-dimensional observations</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Source"><span class="nav-number">2.2.1.</span> <span class="nav-text">Source</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Model-selection-choosing-estimators-and-their-parameters"><span class="nav-number">2.3.</span> <span class="nav-text">Model selection: choosing estimators and their parameters</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Score-and-cross-validated-scores"><span class="nav-number">2.3.1.</span> <span class="nav-text">Score, and cross-validated scores</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#KFold-cross-validation"><span class="nav-number">2.3.1.1.</span> <span class="nav-text">KFold cross validation</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Cross-validation-generators"><span class="nav-number">2.3.2.</span> <span class="nav-text">Cross-validation generators</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Cross-validation-generators-1"><span class="nav-number">2.3.3.</span> <span class="nav-text">Cross-validation generators</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Grid-search-and-cross-validated-estimators"><span class="nav-number">2.3.4.</span> <span class="nav-text">Grid-search and cross-validated estimators</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Source-1"><span class="nav-number">2.3.5.</span> <span class="nav-text">Source</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Unsupervised-learning-seeking-representations-of-the-data"><span class="nav-number">2.4.</span> <span class="nav-text">Unsupervised learning: seeking representations of the data</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Clustering-grouping-observations-together"><span class="nav-number">2.4.1.</span> <span class="nav-text">Clustering: grouping observations together</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#K-means-clustering"><span class="nav-number">2.4.2.</span> <span class="nav-text">K-means clustering</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Decompositions-from-a-signal-to-components-and-loadings"><span class="nav-number">2.4.3.</span> <span class="nav-text">Decompositions: from a signal to components and loadings</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#Principal-component-analysis-PCA"><span class="nav-number">2.4.3.1.</span> <span class="nav-text">Principal component analysis: PCA</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Independent-Component-Analysis-ICA"><span class="nav-number">2.4.3.2.</span> <span class="nav-text">Independent Component Analysis: ICA</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Source-2"><span class="nav-number">2.4.4.</span> <span class="nav-text">Source</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Putting-it-all-together"><span class="nav-number">2.5.</span> <span class="nav-text">Putting it all together</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Pipelining"><span class="nav-number">2.5.1.</span> <span class="nav-text">Pipelining</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Face-recognition-with-eigenfaces"><span class="nav-number">2.5.2.</span> <span class="nav-text">Face recognition with eigenfaces</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Working-With-Text-Data"><span class="nav-number">3.</span> <span class="nav-text">Working With Text Data</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Working-With-Text-Data-1"><span class="nav-number">3.1.</span> <span class="nav-text">Working With Text Data</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Extracting-features-from-text-files"><span class="nav-number">3.2.</span> <span class="nav-text">Extracting features from text files</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Bags-of-words"><span class="nav-number">3.2.1.</span> <span class="nav-text">Bags of words</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Choosing-the-right-estimator"><span class="nav-number">4.</span> <span class="nav-text">Choosing the right estimator</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">东木金</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Gemini
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'manual') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
